<template>
  <view class="chat-container">
    <!-- 聊天消息区域 -->
    <scroll-view
        class="chat-messages"
        scroll-y="true"
        :scroll-top="scrollTop"
        :scroll-into-view="'msg-' + (messages.length - 1)"
        enhanced="true">

      <view
          v-for="(message, index) in messages"
          :key="index"
          :id="'msg-' + index"
          class="message-item">

        <!-- 用户消息（右侧） -->
        <view v-if="message.type === 'user'" class="message-wrapper user-message">
          <view class="message-bubble user-bubble">
            <text class="message-text">{{ message.content }}</text>
            <view class="message-time">{{ message.time }}</view>
          </view>
          <view class="avatar user-avatar">我</view>
        </view>

        <!-- 系统消息（左侧） -->
        <view v-else class="message-wrapper system-message">
          <view class="avatar system-avatar">{{ message.category }}</view>
          <view class="message-bubble system-bubble">
            <!-- 使用消息展示组件 -->
            <MessageDisplay
                :message="message"
                @movie-click="handleMovieClick"
                @game-click="handleGameClick" />

            <view class="message-time">{{ message.time }}</view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 分组选择器 -->
    <view class="category-selector">
      <scroll-view scroll-x="true" class="category-scroll">
        <view class="category-tabs">
          <view
              v-for="(category, index) in categories"
              :key="index"
              :class="['category-tab', { active: selectedCategory === category.key }]"
              @click="selectCategory(category.key)">
            <uni-icons :type="category.icon" size="20"></uni-icons>
            <text class="category-text">{{ category.name }}</text>
          </view>

          <!-- 下载管理快捷按钮 -->
          <view
              class="category-tab download-tab"
              @click="navigateToDownloads">
            <uni-icons type="download" size="20"></uni-icons>
            <text class="category-text">下载</text>
          </view>

          <!-- 聊天历史管理 -->
          <view
              class="category-tab history-tab"
              @click="showHistoryMenu">
            <uni-icons type="list" size="20"></uni-icons>
            <text class="category-text">历史</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 输入框区域 -->
    <view class="input-area">
      <view class="input-wrapper">
        <input
            v-model="inputMessage"
            class="chat-input"
            type="text"
            :placeholder="'向' + getCurrentCategoryName() + '发送消息...'"
            @confirm="sendMessage"
            confirm-type="send" />
        <button
            class="send-button"
            type="primary"
            @click="sendMessage"
            :disabled="!inputMessage.trim() || isNavigating">
          {{ isNavigating ? '发送中...' : '发送' }}
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { sendChatMessage } from '@/api/mywork/chat/index.js'
import MessageDisplay from './components/MessageDisplay.vue'
import DownloadManager from './utils/DownloadManager.js'
import ChatHistory from './utils/ChatHistory.js'
import { chatCategories, getCategoryName } from './config/categories.js'

export default {
  name: 'ChatIndex',
  components: {
    MessageDisplay
  },
  data() {
    return {
      inputMessage: '',
      scrollTop: 0,
      selectedCategory: 'novel', // 默认选择小说
      isNavigating: false, // 发送状态标识
      messages: [],
      categories: chatCategories
    }
  },

  methods: {
    // 选择分组
    selectCategory(categoryKey) {
      this.selectedCategory = categoryKey
      console.log('选择分组:', categoryKey)
    },

    // 获取当前分组名称
    getCurrentCategoryName() {
      return getCategoryName(this.selectedCategory)
    },

    // 发送消息
    async sendMessage() {
      if (!this.inputMessage.trim() || this.isNavigating) {
        return
      }

      // 设置发送状态
      this.isNavigating = true

      const userMessage = {
        type: 'user',
        content: this.inputMessage.trim(),
        time: this.formatTime(new Date()),
        category: this.selectedCategory
      }

      // 添加用户消息到聊天记录
      this.messages.push(userMessage)

      // 保存到本地存储
      ChatHistory.addMessage({
        type: 'text',
        content: userMessage.content,
        sender: 'user',
        category: this.selectedCategory
      })

      // 保存输入的消息，然后清空输入框
      const messageToSend = this.inputMessage.trim()
      this.inputMessage = ''

      // 滚动到底部
      this.scrollToBottom()

      try {
        // 显示正在输入状态
        const typingMessage = {
          type: 'system',
          content: '正在思考中...',
          time: this.formatTime(new Date()),
          category: this.getCurrentCategoryName()
        }
        this.messages.push(typingMessage)
        this.scrollToBottom()

        // 发送到后端
        console.log('准备发送消息到后端:', {
          message: messageToSend,
          category: this.selectedCategory
        })

        const response = await sendChatMessage({
          message: messageToSend,
          category: this.selectedCategory
        })

        console.log('后端响应:', response)

        // 移除"正在思考"消息
        this.messages.pop()

        // 处理特殊数据类型的响应
        const systemMessage = this.buildSystemMessage(response)
        this.messages.push(systemMessage)

        // 保存系统回复到本地存储
        const messageType = this.getMessageType(response)
        ChatHistory.addMessage({
          type: messageType,
          content: systemMessage.content,
          sender: 'system',
          category: this.selectedCategory,
          data: response.data // 保存原始数据
        })

      } catch (error) {
        // 移除"正在思考"消息
        this.messages.pop()

        console.error('发送消息失败:', error)
        const errorMessage = {
          type: 'system',
          content: '抱歉，消息发送失败，请稍后重试',
          time: this.formatTime(new Date()),
          category: this.getCurrentCategoryName()
        }
        this.messages.push(errorMessage)

        // 保存错误消息
        ChatHistory.addMessage({
          type: 'system',
          content: errorMessage.content,
          sender: 'system',
          category: this.selectedCategory
        })
      } finally {
        // 无论成功失败都要重置发送状态
        this.isNavigating = false
      }

      this.scrollToBottom()
    },

    // 构建系统消息
    buildSystemMessage(response) {
      console.log('构建系统消息 - 当前分组:', this.selectedCategory)
      console.log('构建系统消息 - 响应数据:', response)

      const baseMessage = {
        type: 'system',
        time: this.formatTime(new Date()),
        category: this.getCurrentCategoryName()
      }

      // 处理电影数据
      if (this.selectedCategory === 'movie' && response.data && Array.isArray(response.data)) {
        console.log('处理电影数据:', response.data)
        return {
          ...baseMessage,
          content: `找到 ${response.data.length} 部电影，点击下载链接可以下载：`,
          movieList: response.data
        }
      }

      // 处理游戏数据
      if (this.selectedCategory === 'game' && response.data && Array.isArray(response.data)) {
        console.log('处理游戏数据:', response.data)
        return {
          ...baseMessage,
          content: `找到 ${response.data.length} 个游戏，点击选择下载方式：`,
          gameList: response.data
        }
      }

      // 普通消息
      console.log('处理普通消息:', response.data || response.message)
      return {
        ...baseMessage,
        content: response.data || response.message || '收到回复'
      }
    },

    // 处理电影点击事件
    handleMovieClick(movie) {
      DownloadManager.handleMovieDownload(movie)
    },

    // 处理游戏点击事件
    handleGameClick(game) {
      DownloadManager.handleGameDownload(game)
    },

    // 导航到下载页面
    navigateToDownloads() {
      uni.navigateTo({
        url: '/pages/work/mytool/downloads/index'
      })
    },

    // 格式化时间
    formatTime(date) {
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `${hours}:${minutes}`
    },

    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        this.scrollTop = 999999
      })
    },

    // 加载聊天历史
    loadChatHistory() {
      try {
        const history = ChatHistory.getRecentMessages(50) // 获取最近50条消息
        this.messages = this.convertHistoryToMessages(history)

        // 如果没有历史记录，显示欢迎消息
        if (this.messages.length === 0) {
          this.messages.push({
            type: 'system',
            content: '你好！我是智能助手，请选择一个分组开始聊天吧！',
            time: this.formatTime(new Date()),
            category: '系统'
          })
        }

        this.scrollToBottom()
      } catch (error) {
        console.log('加载聊天历史失败:', error)
      }
    },

    // 将历史记录转换为消息格式
    convertHistoryToMessages(history) {
      return history.reverse().map(record => {
        const message = {
          type: record.sender === 'user' ? 'user' : 'system',
          content: record.content,
          time: ChatHistory.formatMessageTime(record.timestamp),
          category: record.category || 'general'
        }

        // 如果是游戏或电影数据，添加相应列表
        if (record.data && Array.isArray(record.data)) {
          if (record.type === 'game') {
            message.gameList = record.data
          } else if (record.type === 'movie') {
            message.movieList = record.data
          }
        }

        return message
      })
    },

    // 获取消息类型
    getMessageType(response) {
      if (this.selectedCategory === 'game' && response.data && Array.isArray(response.data)) {
        return 'game'
      }
      if (this.selectedCategory === 'movie' && response.data && Array.isArray(response.data)) {
        return 'movie'
      }
      return 'text'
    },

    // 清空聊天记录
    clearChatHistory() {
      uni.showModal({
        title: '确认清空',
        content: '确定要清空所有聊天记录吗？此操作不可撤销。',
        success: (res) => {
          if (res.confirm) {
            if (ChatHistory.clearChatHistory()) {
              this.messages = []
              this.loadChatHistory() // 重新加载欢迎消息
              uni.showToast({
                title: '聊天记录已清空',
                icon: 'success'
              })
            } else {
              uni.showToast({
                title: '清空失败',
                icon: 'error'
              })
            }
          }
        }
      })
    },

    // 查看聊天统计
    showChatStatistics() {
      const stats = ChatHistory.getStatistics()
      const content = `总消息数：${stats.totalMessages}
文本消息：${stats.textMessages}
游戏消息：${stats.gameMessages}
电影消息：${stats.movieMessages}
今日消息：${stats.todayMessages}
本周消息：${stats.weekMessages}`

      uni.showModal({
        title: '聊天统计',
        content: content,
        showCancel: false
      })
    },

    // 显示历史菜单
    showHistoryMenu() {
      uni.showActionSheet({
        title: '聊天历史管理',
        itemList: ['查看统计', '清空记录', '刷新历史'],
        success: (res) => {
          switch (res.tapIndex) {
            case 0:
              this.showChatStatistics()
              break
            case 1:
              this.clearChatHistory()
              break
            case 2:
              this.loadChatHistory()
              uni.showToast({
                title: '历史记录已刷新',
                icon: 'success'
              })
              break
          }
        }
      })
    }
  },

  onLoad() {
    console.log('聊天页面加载完成')
    this.loadChatHistory()
  },

  onShow() {
    // 页面显示时刷新聊天记录
    this.loadChatHistory()
  }
}
</script>

<style lang="scss" scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.chat-messages {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

.message-item {
  margin-bottom: 15px;
}

.message-wrapper {
  display: flex;
  align-items: flex-end;
}

.user-message {
  justify-content: flex-end;
}

.system-message {
  justify-content: flex-start;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: white;
  margin: 0 8px;
}

.user-avatar {
  background-color: #007aff;
}

.system-avatar {
  background-color: #34c759;
}

.message-bubble {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 18px;
}

.user-bubble {
  background-color: #007aff;
  color: white;
}

.system-bubble {
  background-color: white;
  color: #333;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.message-text {
  font-size: 16px;
  line-height: 1.4;
  word-wrap: break-word;
}

.message-time {
  font-size: 12px;
  margin-top: 4px;
  opacity: 0.7;
}

.category-selector {
  background-color: white;
  border-top: 1px solid #e5e5e5;
  padding: 10px 0;
}

.category-scroll {
  height: 60px;
}

.category-tabs {
  display: flex;
  padding: 0 10px;
}

.category-tab {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 8px 16px;
  margin-right: 10px;
  border-radius: 8px;
  background-color: #f0f0f0;
  min-width: 60px;
}

.category-tab.active {
  background-color: #007aff;
  color: white;
}

.category-tab.download-tab {
  background-color: #ff9500;
  color: white;
  margin-left: 10px;
}

.category-tab.download-tab:active {
  background-color: #e6830e;
}

.category-tab.history-tab {
  background-color: #34c759;
  color: white;
  margin-left: 10px;
}

.category-tab.history-tab:active {
  background-color: #2fb344;
}

.category-text {
  font-size: 12px;
  margin-top: 4px;
}

.input-area {
  background-color: white;
  border-top: 1px solid #e5e5e5;
  padding: 10px;
}

.input-wrapper {
  display: flex;
  align-items: center;
}

.chat-input {
  flex: 1;
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 20px;
  padding: 0 15px;
  font-size: 16px;
  margin-right: 10px;
}

.send-button {
  height: 40px;
  border-radius: 20px;
  padding: 0 20px;
  font-size: 14px;
}

.send-button[disabled] {
  opacity: 0.5;
}
</style>